package net.avh4.scratch.rpg;

import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;

import javax.imageio.ImageIO;

public class TerrainType {
	
	private Image tile;
	
	/** A cached copy of <code>tile</code> scaled to the size of the previous call to draw(). */
	private transient Image cachedTile = null;
	/** The width of the <code>cachedScale</code> image. */
	private transient int cachedWidth = 0;
	/** The height of the <code>cachedScale</code> image. */
	private transient int cachedHeight = 0;
	
	public TerrainType(File imageFile) throws IOException {
		tile = ImageIO.read(imageFile);
	}
	
	public TerrainType(String imageFilename) throws IOException {
		this(new File(imageFilename));
	}
	
	public void draw(Graphics2D g, int x1, int y1, int x2, int y2) {
		int width = Math.abs(x2 - x1);
		int height = Math.abs(y2 - y1);
		if (height == 0 || width == 0) return;
		
		if (cachedTile == null || width != cachedWidth || height != cachedHeight) {
			cachedTile = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
			cachedTile.getGraphics().drawImage(tile, 0, 0, width, height, null);
		}
		
		int x = (x1 < x2) ? x1 : x2;
		int y = (y1 < y2) ? y1 : y2;
		g.drawImage(cachedTile, x, y, null);
	}

}
